<!-- eslint-disable @typescript-eslint/no-unused-vars -->
<!-- eslint-disable prettier/prettier -->
<template>
  <div>
    <div class="card content-box">
      <span class="text">数据组管理</span>
      <el-divider></el-divider>
      <!--搜索-->
      <div class="mt-4" style="display: flex">
        <el-input v-model="input" style="max-width: 600px" placeholder="搜索数据组" class="input-with-select">
          <template #prepend>
            <el-select v-model="select" placeholder="筛选" style="width: 115px">
              <el-option label="数据组名" value="1" />
            </el-select>
          </template>
          <template #append>
            <el-button :icon="Search" @click="search" />
          </template>
        </el-input>

        <el-button :icon="Close" :disabled="!input" @click="cancel" style="margin-left: 10px" />
      </div>
      <div style="width: 100%; display: flex; justify-content: start">
        <el-button type="primary" @click="add_group = true">添加数据组</el-button>
      </div>
      <br />

      <el-table :data="tableData" border class="custom-table" style="width: 100%">
        <el-table-column type="selection" :selectable="selected" width="55" />
        <el-table-column fixed label="序号" width="100" type="index"> </el-table-column>
        <el-table-column label="数据组名称" prop="inspectionGroupName"></el-table-column>
        <el-table-column label="机组" prop="unitName"></el-table-column>
        <el-table-column label="操作" width="200">
          <!--#default="{ row }"-->
          <template #default="{ row }">
            <el-button @click="click_check(row)" size="small">查看</el-button>
            <el-button type="primary" @click="show_edit(row)" size="small">编辑</el-button>
            <el-button type="danger" @click="delGroup(row)" size="small">删除</el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="空空如也" />
        </template>
      </el-table>
      <br />
      <!--分页 后面要根据数据算-->
      <div style="width: 100%; display: flex; justify-content: end">
        <el-pagination
          :current-page="searchData.current"
          :page-size="searchData.limit"
          :total="total"
          :pager-count="7"
          layout="jumper, prev, pager, next, total"
          @current-change="getData"
        />
      </div>
    </div>

    <!--数据组详情抽屉-->
    <el-drawer v-model="show_group" size="60%">
      <div>
        <!--数据组信息-->
        <el-card style="max-width: 100%">
          <template #header>{{ groupName }}</template>
          <div class="common-layout">
            <el-button v-auth="'add'" type="primary" :icon="CirclePlus" @click="add_mem = true">新增属性-单位</el-button>
            <el-table :data="group" style="width: 100%">
              <el-table-column label="序号" width="100" type="index"> </el-table-column>
              <el-table-column label="属性" prop="attribute"></el-table-column>
              <el-table-column label="单位" prop="perUnit"></el-table-column>
              <el-table-column label="操作" width="200">
                <!--#default="{ row }"-->
                <template #default="{ row }">
                  <el-button type="danger" :icon="Delete" circle @click="delMember(row)" />
                </template>
              </el-table-column>
              <template #empty>
                <el-empty description="空空如也" />
              </template>
            </el-table>
          </div>
        </el-card>
      </div>

      <!--向已有数据组添加-->
      <el-dialog v-model="add_mem" title="添加属性-单位" width="30%">
        <div>
          <el-form :model="groupDetail" label-width="130px" style="padding-right: 30px">
            <el-form-item label="属性">
              <el-input v-model="groupDetail.attribute"></el-input>
            </el-form-item>
            <el-form-item label="单位">
              <el-input v-model="groupDetail.perUnit"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="add_mem = false">取消</el-button>
            <el-button type="primary" @click="addMember"> 确认 </el-button>
          </span>
        </template>
      </el-dialog>

      <div></div>
    </el-drawer>

    <!-- 添加数据组弹窗 -->
    <el-dialog v-model="add_group" width="40%" title="新建数据组">
      <el-form :model="groupForm" label-width="130px" style="padding-right: 30px">
        <el-form-item label="数据组名称">
          <el-input v-model="groupForm.inspectionGroupName"></el-input>
        </el-form-item>
        <el-form-item label="机组">
          <el-select v-model="groupForm.unitId" placeholder="选择机组" clearable>
            <el-option v-for="unit in unitArray" :key="unit.unitId" :label="unit.unitName" :value="unit.unitId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div>
        <el-table :data="groupDetails" style="width: 100%" border>
          <el-table-column prop="attribute" label="属性">
            <template #default="scope">
              <el-input v-model="scope.row.attribute" placeholder="请输入属性"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="perUnit" label="单位">
            <template #default="scope">
              <el-input v-model="scope.row.perUnit" placeholder="请输入单位"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button type="danger" size="small" @click="deleteRow1(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <br />
        <el-button @click="addRow1" type="primary">添加行</el-button>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="add_group = false">取消</el-button>
          <el-button type="primary" @click="addGroup"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <!--修改数据组名称-->
    <el-dialog v-model="show_editName" title="修改数据组名称" width="50%">
      <div>
        <el-form :model="groupForm" label-width="130px" style="padding-right: 30px">
          <el-form-item label="数据组名称">
            <el-input v-model="groupForm.inspectionGroupName"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="show_editName = false">取消</el-button>
          <el-button type="primary" @click="editName"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="js" name="departmentManage">
import { onMounted, reactive, ref } from "vue";
import { CirclePlus, Delete, Search, Close } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getDataDeService,
  getDataService,
  addDataService,
  addForDataService,
  editDataNameService,
  delDataInDataService,
  delDataService
} from "@/api/inspection/datas";
import { dataGroupSearchService } from "@/api/systemManage/search";
import request from "@/api/request";

//控制变量
const add_group = ref(false);
const show_editName = ref(false);
const show_group = ref(false);
//const isSure = ref(false);
//const sureContext = ref("");
const add_mem = ref(false);
const groupId = ref(null);
const groupName = ref("");
const unitArray = ref([]);
//用户搜索输入
const input = ref("");
const select = ref("1");

//数据模型
const groups = ref([
  {
    inspectionGroupId: 0,
    inspectionGroupName: ""
  }
]);
const searched = ref([
  {
    inspectionGroupId: 0,
    inspectionGroupName: ""
  }
]);

const groupForm = ref({
  inspectionGroupName: ""
});

//perUnit 单位
const group = ref([
  {
    inspectionGroupId: 0,
    attribute: "",
    groupDetailId: 0,
    perUnit: ""
  }
]);

const groupDetails = ref([
  {
    attribute: "",
    perUnit: ""
  }
]);

const groupDetail = ref({
  attribute: "",
  perUnit: ""
});

//分页
const total = ref(groups.value.length);
// searchData-向后端分页查询的对象，即当前页和每页总数
const searchData = reactive({
  current: 1,
  limit: 7
});

const tableData = ref([{}]);

//传入分页参数
const pageQuery = (current, limit) => {
  let begin = current * limit - limit;
  //这里不减一是因为，slice方法裁切是左闭右开数组
  let end = current * limit;
  tableData.value = groups.value.slice(begin, end);
};

const getData = newPage => {
  searchData.current = newPage;
  total.value = groups.value.length;
  pageQuery(searchData.current, searchData.limit);
};

const getGroupList = async () => {
  let result = await getDataService();
  console.log(result.data.data);
  groups.value = result.data.data;
  total.value = groups.value.length;
  getData(1);
};
onMounted(getGroupList);
const getAllUnits = () => {
  request.get("/api-self/users/unit/getUnits").then(res => {
    const data = res.data;
    if (data.code === 0) {
      unitArray.value = data.data;
    } else {
      ElMessage.error("获取机组数据失败：" + data.message);
    }
  });
};
onMounted(getAllUnits);
const getGroupDetail = async id => {
  //console.log("获取袭击" + id);
  let result = await getDataDeService(id);
  group.value = result.data.data;
  console.log("详情" + result.data.data);
};

const click_check = row => {
  groupId.value = row.inspectionGroupId;
  //console.log("点击" + groupId.value);
  groupName.value = row.inspectionGroupName;
  getGroupDetail(groupId.value);
  show_group.value = true;
};

const show_edit = row => {
  //groupForm.value.class_name = row.class_name;
  groupForm.value.inspectionGroupName = row.inspectionGroupName;
  groupForm.value.inspectionGroupId = row.inspectionGroupId;
  //console.log("")
  //getGroupDetail(row.inspectionGroupId);
  show_editName.value = true;
};

const editName = async () => {
  await editDataNameService(groupForm.value);
  ElMessage.success("修改成功");
  groupForm.value.inspectionGroupId = 0;
  groupForm.value.inspectionGroupName = "";
  getGroupList();
  show_editName.value = false;
};

const addGroup = async () => {
  let dataObj = {
    inspectionGroupName: groupForm.value.inspectionGroupName,
    groupDetails: groupDetails.value,
    unitId: groupForm.value.unitId
  };
  const result = await addDataService(dataObj);
  if (result.data.code === 0) {
    ElMessage.success("添加成功");
    groupForm.value.inspectionGroupName = "";
    groupDetails.value = [
      {
        attribute: "",
        perUnit: ""
      }
    ];
    add_group.value = false;
    getGroupList();
  } else {
    ElMessage.error("添加失败：" + result.data.message);
  }
};

//添加新的数据对,为已有数据组新增数据
const addMember = async () => {
  let dataObj = {
    inspectionGroupId: groupId.value,
    data: groupDetail.value
  };
  await addForDataService(dataObj);
  ElMessage.success("添加成功");
  add_mem.value = false;
  groupDetail.value = {
    attribute: "",
    perUnit: ""
  };
  getGroupDetail(groupId.value);
};

const delGroup = async row => {
  ElMessageBox.confirm("确认删除该数据组?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    let dataObj = {
      inspectionGroupId: row.inspectionGroupId
    };
    const res = await delDataService(dataObj);
    if (res.data.code === 0) {
      ElMessage.success(row.inspectionGroupName + "删除成功");
      getGroupList();
    } else {
      ElMessage.error("删除失败：" + res.data.message);
    }
  });
};

const delMember = async row => {
  let dataObj = {
    groupDetailId: row.groupDetailId
  };
  await delDataInDataService(dataObj);
  getGroupDetail(groupId.value);
  ElMessage.success("删除成功");
};

//添加多个属性和单位
const deleteRow1 = item => {
  const index = item;
  if (index !== -1) {
    groupDetails.value.splice(index, 1);
  }
};

const addRow1 = () => {
  groupDetails.value.push({
    attribute: "",
    perUnit: ""
  });
};

const changeunitIdToUnitName = unitId => {
  const unit = unitArray.value.find(unit => unit.unitId == unitId);
  if (unit) {
    return unit.unitName;
  } else {
    return null;
  }
};

//搜索
const search = async () => {
  let dataObj = {};
  if (select.value == "1") {
    dataObj = {
      inspectionGroupName: input.value
    };
    let result = await dataGroupSearchService(dataObj);
    searched.value = result.data.data;
    tableData.value = searched.value;
    tableData.value.forEach(item => {
      item.unitName = changeunitIdToUnitName(item.unitId);
    });
  }
};
const cancel = () => {
  input.value = "";
  tableData.value = groups.value;
};

const selected = () => {
  return true;
};
</script>

<style scoped>
.demo-tabs > .el-tabs__content {
  padding: 32px;
  font-size: 32px;
  font-weight: 600;
  color: #6b778c;
}
.demo-tabs {
  margin-top: -20px;
}
.topadd {
  position: absolute;
  top: 73px;
  right: 40px;
}
.page-container {
  box-sizing: border-box;
  min-height: 100%;
}
.add {
  position: absolute;
  top: 80%;
  right: 3%;
  float: left;
  width: 60px;
  height: 60px;
  font-size: 50px;
  font-weight: 600;
  border-radius: 50%;
}
.inneradd {
  position: absolute;
  top: 55px;
  right: 30px;
  float: left;
  font-weight: 900;
}
.avatar-uploader .avatar {
  display: block;
  width: 178px;
  height: 178px;
}
.avatar-uploader .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  width: 178px;
  height: 178px;
  font-size: 28px;
  color: #060707;
  text-align: center;
}
:deep(.my-label) {
  background: var(--el-color-success-light-9) !important;
}
:deep(.my-content) {
  background: var(--el-color-danger-light-9);
}
.Product-image {
  width: auto; /* 图片宽度自适应 */
  max-width: 100%; /* 图片最大宽度为其容器的100% */
  height: auto; /* 图片高度自适应 */
  max-height: 100%; /* 图片最大高度为其容器的100% */
}
.custom-table :deep(.el-table__header-wrapper thead tr th) {
  color: #000000;
  text-align: center;
  background-color: #fafafa;
}
.custom-table :deep(.el-table__body-wrapper tbody tr td) {
  text-align: center; /* 单元格内容居中 */
}
.el-button {
  border-radius: 6px;
}
</style>
